﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using System.Windows;
using System.Globalization;
using System.Windows.Data;
using System.Xaml;
using System.Reflection;
using System.Windows.Media;

namespace Invini.Tools
{
    public class GetExtension : MarkupExtension
    {
        [ConstructorArgument("property")]
        public string Property
        {
            get;
            set;
        }

        public GetExtension() { }
        public GetExtension(string property)
        {
            this.Property = property;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if(String.IsNullOrEmpty(this.Property))
                throw new InvalidOperationException("Property name is null or empty.");

            if (serviceProvider == null)
                throw new InvalidOperationException("Can't find root element.");

            IRootObjectProvider rootProvider = (IRootObjectProvider)serviceProvider.GetService(typeof(IRootObjectProvider));
            if(rootProvider == null)
                throw new InvalidOperationException("Can't find root element.");
            
            object root = rootProvider.RootObject;
            if(root == null)
                throw new InvalidOperationException("Root is null.");

            Type rootType = root.GetType();
            PropertyInfo propertyInfo = rootType.GetProperty(this.Property, BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if(propertyInfo == null)
                throw new InvalidOperationException("Property does not exist.");

            if(!propertyInfo.CanRead)
                throw new InvalidOperationException("Property cannot be read.");

            return propertyInfo.GetValue(root);
        }
    }
}
